import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import * as API from "../api/http";

const initialState = {
    typelist: [],//类型数据
    shoplist: [],//购车数据
    carlist: [],//存放购物车的数据的数据

}

const todosSlice = createSlice({
    name: "todos",
    initialState,
    reducers: { //同步操作
        //获取类型数据
        t_gettypelist(state, action) {
            state.typelist = action.payload
        },
        //获取购车数据
        t_getshoplist(state, action) {
            state.shoplist = action.payload
        },
        //存放购物车的数据的数据
        t_getcarlist(state, action) {
            state.carlist = action.payload
        },
        //添加购物车数据
        t_addcarlist(state, action) {
            state.carlist.push(action.payload)
        },
        //编辑购物车数据
        t_updatelist(state, action) {
            let i = state.carlist.findIndex(item => {
                return item.id == action.payload.id
            })
            state.carlist[i] = action.payload
        }

    },
});

export const actionfn = todosSlice.actions;
export default todosSlice.reducer;

//异步操作
//获取类型数据
export let async_gettypelist = createAsyncThunk('async_gettypelist', async (_, store) => {
    //调取接口
    let res = await API.http_gettypelist()
    //同步修改异步
    store.dispatch(actionfn.t_gettypelist(res))
})

//获取购车数据
export let async_getshoplist = createAsyncThunk('async_getshoplist', async (_, store) => {
    //调取接口
    let res = await API.http_getshoplist()
    //同步修改异步
    store.dispatch(actionfn.t_getshoplist(res))
})

//存放购物车的数据的数据
export let async_getcarlist = createAsyncThunk('async_getcarlist', async (_, store) => {
    //调取接口
    let res = await API.http_getcarlist()
    //同步修改异步
    store.dispatch(actionfn.t_getcarlist(res))
})

//添加购物车的数据
export let async_addcarlist = createAsyncThunk('async_addcarlist', async (obj, store) => {
    //调取接口
    let res = await API.http_addcarlist(obj)
    //同步修改异步
    store.dispatch(actionfn.t_addcarlist(res))
})

//编辑购物车的数据
export let async_updatecarlist = createAsyncThunk('async_updatecarlist', async (obj, store) => {
    //调取接口
    let res = await API.http_updatecarlist(obj)
    //同步修改异步
    store.dispatch(actionfn.t_updatelist(res))
})


